<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="文件名" prop="sourceFileName">
              <el-input v-model="queryParams.sourceFileName" placeholder="请输入文件名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="转换类型" prop="convertType">
              <el-input v-model="queryParams.convertType" placeholder="请输入文件名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="输入模型" prop="inputType">
              <el-input v-model="queryParams.inputType" placeholder="请输入文件名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="输出模型" prop="outputType">
              <el-input v-model="queryParams.outputType" placeholder="请输入文件名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="状态" clearable>
                <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="创建时间" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              ></el-date-picker>
            </el-form-item> -->

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button v-hasPermi="['cax:target:delete']" type="danger" plain icon="Delete" @click="handleDelete()">删除</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table ref="multipleTableRef" v-loading="loading" :data="caxConvertInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="80" />
        <el-table-column label="转换类型" prop="convertType" min-width="100" />
        <el-table-column label="源文件名" prop="sourceFileName" :show-overflow-tooltip="true" min-width="150" />
        <el-table-column label="输入模型" prop="inputType" min-width="100" />
        <el-table-column label="输出模型" prop="outputType" min-width="100" />
        <el-table-column label="来源" prop="source" min-width="100" />
        <el-table-column label="创建人" prop="createByName" min-width="100" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            {{ getLabelByValue(statusOptions, scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-tooltip content="下载源文件" placement="top">
              <el-button
                v-hasPermi="['cax:source:download']"
                link
                type="primary"
                icon="Download"
                @click="handleSourceDownload(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="下载转换文件" placement="top">
              <el-button
                v-if="scope.row.status === '1'"
                v-hasPermi="['cax:target:download']"
                link
                type="primary"
                icon="Download"
                @click="handleTargetDownload(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['cax:target:delete']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script setup name="caxConversionPlatformList" lang="ts">
import { getCaxConvertInfoList, downloadCaxSource, downloadCaxTarget, delCaxConvertInfo } from '@/api/caxConversionPlatform/index';
import { caxConvertInfoVO, caxConvertInfoForm, caxConvertInfoQuery, optionType } from '@/api/caxConversionPlatform/type';
import { ModelTypeEnum } from '@/enums/ModelTypeEnum';
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const caxConvertInfoList = ref<caxConvertInfoVO[]>();
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();

const initForm: caxConvertInfoForm = {
  convertType: '',
  inputType: '',
  outputType: '',
  file: undefined
};
const statusOptions: Array<optionType> = [
  {
    value: '0',
    label: '转换中'
  },
  {
    value: '1',
    label: '转换成功'
  },
  {
    value: '2',
    label: '转换失败'
  }
];

const data = reactive<PageData<caxConvertInfoForm, caxConvertInfoQuery>>({
  form: { ...initForm },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sourceFileName: '',
    convertType: '',
    inputType: '',
    outputType: '',
    status: ''
  },
  rules: undefined
});
const { queryParams } = toRefs(data);

/**
 * 查询角色列表
 */
const getList = () => {
  loading.value = true;
  getCaxConvertInfoList(proxy?.addDateRange(queryParams.value, dateRange.value)).then((res) => {
    caxConvertInfoList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  });
};

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};
const handleSelectionChange = (val: caxConvertInfoVO[]) => {
  ids.value = val.map((item) => item.id);
};
/**删除按钮操作 */
const handleDelete = async (row?: caxConvertInfoVO) => {
  const id = row?.id || ids.value + '';
  if (!id) {
    await proxy?.$modal.msgWarning('请选择要删除的数据！');
    return false;
  }
  await proxy?.$modal.confirm('是否确认删除选择数据！');
  await delCaxConvertInfo(id);
  getList();
  proxy?.$modal.msgSuccess('删除成功');
};
const handleConvert = () => {
  router.push({ path: '/cax-tp/conversion' });
};
const getLabelByValue = (arr: Array<optionType>, value: string) => {
  const obj = arr.find((item) => item.value === value);
  if (obj) {
    return obj.label;
  }
  return value;
};
const downloadFile = (res, fileName) => {
  const blob = new Blob([res]);
  const objUrl = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.setAttribute('href', objUrl);
  link.setAttribute('download', fileName);
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
/** 导出按钮操作 */
const handleSourceDownload = (row?: caxConvertInfoVO) => {
  downloadCaxSource(row.id).then((res) => {
    downloadFile(res, row.sourceFileName);
  });
};
/** 导出按钮操作 */
const handleTargetDownload = (row?: caxConvertInfoVO) => {
  downloadCaxTarget(row.id).then((res) => {
    const fileName =
      row.sourceFileName.substring(0, row.sourceFileName.lastIndexOf('.')) +
      '.' +
      (ModelTypeEnum[row.outputType] || row.outputType.toLocaleLowerCase());
    downloadFile(res, fileName);
  });
};
onMounted(() => {
  getList();
});
</script>
